import { useFetch, UseFetchOptions } from '#app'
import { useMessage } from 'naive-ui'
//  基于useFetch()的网络请求封装
//定义ts变量类型接口
interface HttpParms {
    url: string,      //请求api接口地址
    method?: any,   //请求方法
    query?: any,       //添加查询搜索参数到URL
    body?: any         //请求体
}

/**
 * 网络请求方法
 * @param obj 请求参数
 * @returns 响应结果
 */
export const $https = (obj: HttpParms) => {
    const message = useMessage();
    // 环境api
    const appConfig = useRuntimeConfig()
    const baseURL = 'http://localhost:8081/api/'

    const res = new Promise<void>((resolve, reject) => {
        useFetch(
            baseURL + obj.url,
            {
                method: obj.method ?? "GET",
                query: obj?.query ?? null,
                body: obj?.body ?? null,
                onRequest({ request, options }) {
                    // 设置请求报头
                    options.headers = options.headers || {}
                    // options.headers.webToken = localStorage.getItem('token')?localStorage.getItem('token'):''
                },
                onRequestError({ request, options, error }) {
                    // 处理请求错误
                    message.warning('Request Error');
                    reject(error)
                },
                onResponse({ request, response, options }) {
                    // 处理响应数据
                    console.log(response._data)
                    if (response._data.code !== 200) {
                        resolve(response._data)
                    } else {
                        resolve(response._data)
                    }
                },
                onResponseError({ request, response, options }) {
                    console.log(options)
                    message.warning('Request Error');
                    // 处理响应错误
                    reject(options)
                }
            },
        )
    })
    return res;
}